<?php

/**
 * This file is part of easyCMS.
 *
 * (c) 2023 easyCMS <easyCMS@easycms.net.cn>
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

use app\admin\model\BaseModel;
use app\admin\model\SystemAdmin;
use app\admin\model\SystemRoleRight;

/**
 * 当前管理员id
 */
function admin_id(): ?int
{
    return session('admin.id');
}

/**
 * 当前管理员
 *
 * @return array|mixed|null
 */
function admin(array|string|null $fields = null): mixed
{
    refresh_admin_session();
    if (! $admin = session('admin')) {
        return null;
    }
    if ($fields === null) {
        return $admin;
    }
    if (is_array($fields)) {
        $results = [];

        foreach ($fields as $field) {
            $results[$field] = $admin[$field] ?? null;
        }

        return $results;
    }

    return $admin[$fields] ?? null;
}

/**
 * 当前登录用户id
 */
function user_id(): ?int
{
    return session('user.id');
}

/**
 * 当前登录用户
 *
 * @return array|mixed|null
 */
function user(array|string|null $fields = null): mixed
{
    refresh_user_session();
    if (! $user = session('user')) {
        return null;
    }
    if ($fields === null) {
        return $user;
    }
    if (is_array($fields)) {
        $results = [];

        foreach ($fields as $field) {
            $results[$field] = $user[$field] ?? null;
        }

        return $results;
    }

    return $user[$fields] ?? null;
}

/**
 * 刷新当前管理员session
 *
 * @return void
 */
function refresh_admin_session(bool $force = false)
{
    if (! $admin_id = admin_id()) {
        return null;
    }
    $time_now = time();
    // session在2秒内不刷新
    $session_ttl              = 2;
    $session_last_update_time = session('admin.session_last_update_time', 0);
    if (! $force && $time_now - $session_last_update_time < $session_ttl) {
        return null;
    }
    $session  = request()->session();
    $adminObj = SystemAdmin::find($admin_id);
    if (! $adminObj) {
        $session->forget('admin');

        return null;
    }
    $admin = $adminObj->toArray();
    unset($admin['password']);
    // 账户被禁用
    if ($admin['is_lock'] === BaseModel::LOCK_YES) {
        $session->forget('admin');

        return;
    }

    $roleIds = [];
    $permits = [];
    if ($admin['user_type'] !== SystemAdmin::SUPER_ADMIN) {
        // 查询roleId
        $roleIdList = $adminObj->roles()->get()->toArray();

        foreach ($roleIdList as $r) {
            $roleIds[] = $r['id'];
        }
        // 查询permits
        $permitsList = SystemRoleRight::select('m.permits as permits')->whereIn('role_id', $roleIds)
            ->leftJoin('system_menu as m', 'system_role_right.menu_id', '=', 'm.id')
            ->get()->toArray();

        foreach ($permitsList as $p) {
            $permits[] = $p['permits'];
        }
    }
    $admin['roleIds']                  = $roleIds;
    $admin['permits']                  = $permits;
    $admin['session_last_update_time'] = $time_now;
    $session->set('admin', $admin);
}

/**
 * 刷新当前用户session
 *
 * @return void
 */
function refresh_user_session(bool $force = false)
{
    if (! $user_id = user_id()) {
        return null;
    }
    $time_now = time();
    // session在2秒内不刷新
    $session_ttl              = 2;
    $session_last_update_time = session('user.session_last_update_time', 0);
    if (! $force && $time_now - $session_last_update_time < $session_ttl) {
        return null;
    }
    $session = request()->session();
    $user    = ShopManager::find($user_id);
    if (! $user) {
        $session->forget('user');

        return null;
    }
    $user = $user->toArray();
    unset($user['password']);
    $user['session_last_update_time'] = $time_now;
    $session->set('user', $user);
}

function makeDir($path): void
{
    if (! file_exists($path)) {
        makeDir(dirname($path));
        mkdir($path, 0777);
    }
}

/**
 * function：计算两个日期相隔多少年，多少月，多少天
 * param string $date1[格式如：2011-11-5]
 * param string $date2[格式如：2012-12-01]
 * return array array('年','月','日');
 *
 * @throws Exception
 */
function diffDate(string $date1, string $date2): array
{
    $datetime1 = new \DateTime($date1);
    $datetime2 = new \DateTime($date2);
    $interval  = $datetime1->diff($datetime2);
    $time['y'] = $interval->format('%Y');
    $time['m'] = $interval->format('%m');
    $time['d'] = $interval->format('%d');
    $time['h'] = $interval->format('%H');
    $time['i'] = $interval->format('%i');
    $time['s'] = $interval->format('%s');
    $time['a'] = $interval->format('%a');    // 两个时间相差总天数

    return $time;
}
